from flask import Blueprint, render_template, request, flash, redirect, jsonify, session, url_for
from applications.models.frontend import *  # 确保导入前台用户模型
from .form_valider import Login, Register
from werkzeug.security import generate_password_hash, check_password_hash

# 创建前台平台
bp = Blueprint('login', __name__)


# 前台登录
@bp.route('/login', methods=['GET', 'POST'])
def login():
    # 检查用户是否已登录
    if 'user_id' in session:
        return redirect(url_for('/'))  # 重定向到主页或用户仪表板

    if request.method == 'GET':
        next_page = request.args.get('next', '/')
        session['next'] = next_page
        return render_template('user/login/login.html')
    elif request.method == 'POST':
        form = Login(request.form)
        if form.validate():
            username = form.username.data
            password = request.form.get('password').strip()
            user = User.query.filter_by(username=username).first()
            
            # 验证用户名和密码
            if user and check_password_hash(user.password, password):  # 使用 check_password_hash 验证密码
            # if user and password == user.password:  # 不使用 check_password_hash 验证密码
                if user.enable == 0:  # 用户被禁用
                    return jsonify({'code': 403, 'msg': '该用户已被禁用，请联系管理员！'}), 403
                
                session['user_id'] = user.id  # 使用 session 记录登录状态
                print('登录成功', session['user_id'])
                print('当前 Session:', session)

                # 将未登录时的购物车数据迁移到数据库
                if 'cart' in session:
                    for flower_id, quantity in session['cart'].items():
                        cart_item = Cart.query.filter_by(user_id=user.id, flower_id=flower_id).first()
                        if cart_item:
                            cart_item.quantity += quantity  # 增加数量
                        else:
                            cart_item = Cart(user_id=user.id, flower_id=flower_id, quantity=quantity)
                            db.session.add(cart_item)
                    db.session.commit()  # 提交更改
                    session.pop('cart', None)  # 清空 session 中的购物车数据

                # 返回成功信息
                return jsonify({'code': 200, 'msg': '登录成功！', 'user_id': user.id})
            else:
                return jsonify({'code': 401, 'msg': '用户名或密码错误！'})
        else:
            # 将表单验证错误信息传递到 JSON 响应
            print('表单验证错误:', form.errors)
            errors = {field: form.errors[field][0] for field in form.errors}
            return jsonify({'code': 400, 'msg': '表单验证失败,请重新输入正确账号密码！\n'+ str(errors)})

# 前台注册
@bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('user/login/register.html')
    elif request.method == 'POST':
        # 表单验证
        form = Register(request.form)
        if form.validate():
            phone = request.form.get('phone')
            username = form.username.data
            password = form.password.data
            hashed_password = generate_password_hash(password)  # 使用 generate_password_hash 加密密码
            user = User(phone=phone, username=username, password=hashed_password)
            db.session.add(user)
            db.session.commit()
            return jsonify(success=True, msg='添加成功', code=200)
        else:
            print(form.errors)
            return jsonify(success=False, msg=str(form.errors), code=400)

# 退出登录
@bp.route('/logout')
def logout():
    if 'user_id' in session:
        session.pop('user_id')
        session.clear()
    res = redirect('/')
    res.delete_cookie('user_id')
    return res

@bp.route('/phone_login', methods=['POST'])
def phone_login():
    phone = request.form.get('phone')
    code = request.form.get('code')
    # 验证手机号和验证码
    # ...
    return jsonify(success=True)
